﻿/*
 * Author: Fedor Tyurin
 * Distributed under New BSD License
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.IO;

namespace sqlcerun
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("SQL CE code executor");
            if (args.Length != 2)
            {
                Console.WriteLine("2 parameters are required: 1 - database file name, 2 - source code file name.");
                return;
            }
            string fileName = args[0];
            string connectionString = "DataSource=\"" + fileName + "\"";

            if (!File.Exists(fileName))
            {
                SqlCeEngine en = new SqlCeEngine(connectionString);
                en.CreateDatabase();
                en.Dispose();
            }

            SqlCeConnection conn = null;
            try
            {
                conn = new SqlCeConnection(connectionString);
                conn.Open();

                StreamReader sr = new StreamReader(args[1]);
                string query = "";
                string line = sr.ReadLine();
                while (line != null)
                {
                    query += line;
                    if (line.TrimEnd().EndsWith(";"))
                    {
                        Console.WriteLine(query);
                        SqlCeCommand cmd = conn.CreateCommand();
                        cmd.CommandText = query;
                        cmd.ExecuteReader();
                        Console.WriteLine("OK");
                        query = "";
                    }
                    line = sr.ReadLine();
                }
                sr.Close();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
                Console.WriteLine("Failed!");
                return;
            }
            finally
            {
                conn.Close();
            }
            Console.WriteLine("Done!");
        }
    }
}
